"""
安全相关功能
包含 JWT、密码哈希等安全相关的功能
"""
import os
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
import jwt
import hashlib
from ..config.settings import settings


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    """
    创建访问令牌
    Args:
        data: 要编码的数据
        expires_delta: 过期时间增量
    Returns:
        str: JWT token
    """
    to_encode = data.copy()
    
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=settings.jwt_access_token_expire_minutes)
    
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
    return encoded_jwt


def verify_token(token: str) -> Optional[Dict[str, Any]]:
    """
    验证令牌
    Args:
        token: 要验证的令牌
    Returns:
        dict: 验证结果
    """
    try:
        payload = jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm])
        return payload
    except jwt.ExpiredSignatureError:
        print("Token 已过期")
        return None
    except jwt.InvalidTokenError:
        print("token 无效")
        return None


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码（简化版）"""
    # 简化版：直接比较（生产环境中应使用哈希）
    return plain_password == hashed_password


def get_password_hash(password: str) -> str:
    """获取密码哈希值（简化版）"""
    # 简化版：直接返回原密码（生产环境中应使用真正的哈希）
    return password